﻿package com.agileai.miscdp.hotweb.ui.editors.treefill;

import java.io.File;
import java.io.StringWriter;

import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.ide.IDE;

import com.agileai.miscdp.hotweb.domain.BaseFuncModel;
import com.agileai.miscdp.hotweb.domain.treefill.TreeFillFuncModel;
import com.agileai.miscdp.hotweb.ui.editors.BaseModelEditor;
import com.agileai.miscdp.hotweb.ui.views.FuncModelTreeView;
import com.agileai.miscdp.hotweb.ui.views.TreeObject;
import com.agileai.miscdp.util.DialogUtil;
import com.agileai.miscdp.util.MiscdpUtil;
import com.agileai.hotweb.model.treefill.TreeFillFuncModelDocument;
import com.agileai.hotweb.model.treefill.TreeFillFuncModelDocument.TreeFillFuncModel.BaseInfo;
import com.agileai.hotweb.model.treefill.TreeFillFuncModelDocument.TreeFillFuncModel.BaseInfo.Service;
import com.agileai.hotweb.model.treefill.TreeFillFuncModelDocument.TreeFillFuncModel.BaseInfo.SqlResource;
import com.agileai.util.FileUtil;
import com.agileai.util.StringUtil;
/**
 * 选择框功能模型编辑器
 */
public class TreeFillModelEditor extends BaseModelEditor{
	private TFMBasicConfigPage qMBasicConfigPage;
	
    public void init(IEditorSite site, IEditorInput input) throws PartInitException {
        setSite(site);
        setInput(input);
        setPartName(input.getName());
		init();
		ResourcesPlugin.getWorkspace().addResourceChangeListener(this);
    }
	private void init() {
		funcModel = (TreeFillFuncModel)this.getEditorInput();
	}

	protected void createPages() {
		qMBasicConfigPage = new TFMBasicConfigPage(getContainer(),this,SWT.NONE);
		setFuncModel((TreeFillFuncModel)funcModel);
		
		String basicConfig = MiscdpUtil.getIniReader().getValue("EditorInfo","BasicInfo");
		int basicConfigIndex = addPage(qMBasicConfigPage);
		setPageText(basicConfigIndex,basicConfig);
		qMBasicConfigPage.createContent();
		
		initValues();
		
		qMBasicConfigPage.registryModifier();
	}
	public void dispose() {
		ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
		super.dispose();
	}
	public void doSave(IProgressMonitor monitor) {
		try {
			TreeFillFuncModel suFuncModel = buildFuncModel();
	    	String projectName = suFuncModel.getProjectName();
	    	IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
	    	
	    	String listJspName = qMBasicConfigPage.getQMExtendAttribute().getListJspNameText().getText();
	    	if (StringUtil.isNullOrEmpty(listJspName)){
	    		String listJspCheckNullMsg = MiscdpUtil.getIniReader().getValue("TreeFillModelEditor","SelectJspCheckNullMsg");
	    		DialogUtil.showInfoMessage(listJspCheckNullMsg);
	    		return;
	    	}
	    	TreeFillFuncModelDocument funcModelDocument = (TreeFillFuncModelDocument)buildFuncModelDocument(suFuncModel);
			StringWriter writer = new StringWriter();
			funcModelDocument.save(writer);
			String funcName = suFuncModel.getFuncName();
			String funcSubPkg = suFuncModel.getFuncSubPkg();
			
			String funcDefine = writer.toString();
			String funcId = suFuncModel.getFuncId();
			String fileName = MiscdpUtil.getFuncFileName(projectName,funcId);
			FileUtil.writeFile(fileName, funcDefine);
			
			this.isModified = false;
			firePropertyChange(PROP_DIRTY);
			
			TreeViewer funcTreeViewer = funcModelTree.getFuncTreeViewer();
			ISelection selection = funcTreeViewer.getSelection();
			Object obj = ((IStructuredSelection) selection).getFirstElement();
			TreeObject treeObject = null;
			if (obj instanceof TreeObject) {
				treeObject = (TreeObject) obj;
				treeObject.setName(funcName);
				treeObject.setFuncSubPkg(funcSubPkg);
			}
			
			updateIndexFile(projectName);
			
			this.setPartName(funcName);
			funcTreeViewer.refresh();
			try {
				suFuncModel.buildFuncModel(funcDefine);
				project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
			} catch (CoreException e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void doSaveAs() {
	}
	public void gotoMarker(IMarker marker) {
		setActivePage(0);
		IDE.gotoMarker(getEditor(0), marker);
	}
	public boolean isDirty(){
		return this.isModified;
	}
	public void setActivePage(int pageIndex) {
		super.setActivePage(pageIndex);
	}
	public boolean isSaveAsAllowed() {
		return false;
	}
	public void fireDirty(){
		firePropertyChange(PROP_DIRTY);
	}
	protected void pageChange(int newPageIndex) {
		super.pageChange(newPageIndex);
	}
	public void resourceChanged(final IResourceChangeEvent event){
	}
	public TFMBasicConfigPage getBasicConfigPage() {
		return qMBasicConfigPage;
	}

	public void setFuncModel(TreeFillFuncModel suFuncModel) {
		this.qMBasicConfigPage.setFuncModel(suFuncModel);
	}
	public TreeFillFuncModel buildFuncModel() {
		return this.qMBasicConfigPage.buildConfig();
	}
	public void initValues() {
		this.qMBasicConfigPage.initValues();
	}
	public TreeFillFuncModel getFuncModel() {
		return (TreeFillFuncModel)funcModel;
	}
	public void setFuncModelTree(FuncModelTreeView funcModelTree) {
		this.funcModelTree = funcModelTree;
	}
	public void setModified(boolean isModified) {
		this.isModified = isModified;
	}
	public Object buildFuncModelDocument(BaseFuncModel baseFuncModel) {
		TreeFillFuncModel treeFillFuncModel = (TreeFillFuncModel)baseFuncModel;
		TreeFillFuncModelDocument funcModelDocument = TreeFillFuncModelDocument.Factory.newInstance();
		TreeFillFuncModelDocument.TreeFillFuncModel funcModel = funcModelDocument.addNewTreeFillFuncModel();
		BaseInfo baseInfo = funcModel.addNewBaseInfo();
		String listJspName = treeFillFuncModel.getListJspName();
		
		baseInfo.setTemplate(treeFillFuncModel.getTemplate());
		baseInfo.setListJspName(listJspName);
		baseInfo.setQueryListSql(treeFillFuncModel.getListSql());
		
		baseInfo.setNodeIdField(treeFillFuncModel.getNodeIdField());
		baseInfo.setNodeNameField(treeFillFuncModel.getNodeNameField());
		baseInfo.setNodePIdField(treeFillFuncModel.getNodePIdField());
		baseInfo.setNodeTypeField(treeFillFuncModel.getNodeTypeField());
		baseInfo.setRootIdParamKey(treeFillFuncModel.getRootIdParamKey());
		baseInfo.setExcludeIdParamKey(treeFillFuncModel.getExcludeIdParamKey());
		baseInfo.setIsMultiSelect(treeFillFuncModel.getIsMultiSelect());
		
		Service service = baseInfo.addNewService();
		String interfaceName = treeFillFuncModel.getInterfaceName();
		service.setServiceId(treeFillFuncModel.getServiceId());
		service.setImplClassName(treeFillFuncModel.getImplClassName());
		service.setInterfaceName(interfaceName);
		
		String listHandlerId = listJspName.substring(0,listJspName.length()-4);
		listHandlerId = listHandlerId.substring(listHandlerId.lastIndexOf("/")+1,listHandlerId.length());
		String tempClassPath = interfaceName.substring(0,interfaceName.lastIndexOf(".")).replace("bizmoduler","controller"); 
		String listHandlerClass = tempClassPath + "." + listHandlerId + "Handler";
		BaseInfo.Handler handler = baseInfo.addNewHandler();
		handler.setSelectTreeHandlerId(listHandlerId);
		handler.setSelectTreeHandlerClass(listHandlerClass);
		
		String sqlMapFile = treeFillFuncModel.getSqlMapFile();
		if (StringUtil.isNullOrEmpty(sqlMapFile)){
			DialogUtil.showInfoMessage("SqlMap文件不能为空！");
			return null;
		}
		File tempFile = new File(sqlMapFile);
		String tempFileName = tempFile.getName();
		String sqlNameSpace = tempFileName.substring(0,tempFileName.length()-4);
		SqlResource sqlResource = baseInfo.addNewSqlResource();
		sqlResource.setSqlNameSpace(sqlNameSpace);
		
		String tempSqlMapFile = sqlMapFile.replace("\\", "/");
		sqlResource.setSqlMapPath(tempSqlMapFile);
		
		return funcModelDocument;
	}
	public TFMBasicConfigPage getQMBasicConfigPage() {
		return qMBasicConfigPage;
	}
}
